<template>
  <el-dialog
    v-loading="loading || typesLoading"
    :visible="visible"
    :show-close="false"
    :modal="false"
    fullscreen
    append-to-body
  >
    <!--s 导航栏 -->
    <nav class="allot-map-nav mb_12">
      <el-button type="plain-third" size="small" icon="el-icon-back" @click="visible=false">返回列表</el-button>
      <p class="allot-map-tip">地图派单只支持指派拥有客户定位信息且不在审批中的工单。</p>
    </nav>
    <!--e 导航栏 -->
    <div class="allot-map-contaniner">
      <!-- 地图 -->
      <div ref="container" style="height: 100%" @click="infoClick"></div>
      <!--s 地图侧栏 -->
      <div class="allot-map-side" :class="!sideOpen && 'shut'">
        <i class="btn-side iconfont" :class="sideOpen ? 'icon-xiangzuo-copy':'icon-xiangzuo'" @click="sideOpen = !sideOpen"></i>
        <div ref="sideList" class="side-list">
          <div class="side-list-item pointer" 
               v-for="(item, i) in mData" 
               :ref="`side_item_${i}`"
               :class="item.selected && 'selected'"
               :key="i" 
               @click="choose(item, i)">
            <span class="icon_num" >{{i+1}}</span>
            <p>客户姓名: {{item.customerEntity.name}}</p>
            <p>联系人: {{item.linkMan && item.linkMan.name}}</p>
            <p>
              电话: {{item.linkMan && item.linkMan.phone}}
              <el-tooltip class="item" effect="dark" content="拨打电话" placement="top">
                <i class="iconfont icon-fdn-phone" v-if="has_call_center_module" @click.stop="makePhoneCall(item.linkMan && item.linkMan.phone)"></i>
              </el-tooltip>
            </p>
            <p>
              计划时间: {{item.planTime}}
              <i class="iconfont icon-bianji1" v-if="!item.isPaused && !item.inApprove" @click.stop="showEditPlantimeModal()"></i>
            </p>
            <p class="item_text">地址: {{item.address | fmt_address}}</p>
          </div>
          <div class="side-list-loadmore" v-if="hasNextPage">
            <a href="javascript:;" @click="loadmore">加载更多</a>
            <div class="side_list_loadmore" v-if="!hasNextPage && mdata.length <= 0">暂无待指派的工单</div>
          </div>
        </div>
        
        <div class="allot-map-footer pointer" @click="batchAllotOpen">批量指派({{selectedData.length || 0}}/{{mData.length || 0}})</div>
      </div>
      <!--e 地图侧栏 -->
    </div>
    <!-- 调整计划时间弹窗 -->
    <plantime-dialog ref="planTimeDialog"
                     :enable-send-sms="false"
                     :task="currMarkObj.data"
                     :field="planTimeField"
                     :modifiable="taskConfig.taskPlanTime"
                     :success-callback="updatePlanTimeBc"/>
    <!-- 批量指派弹窗 -->
    <batch-allot-dialog ref="batchAllotDialog" :task-id-list="selectedTaskIds" />
  </el-dialog>
</template>

<script>
// api
import * as TaskApi from '@src/api/TaskApi.ts';
// components
import PlanTimeDialog from '../../../../view/components/PlanTimeDialog.vue';
import BatchAllotDialog from '../BatchAllotDialog/BatchAllotDialog.vue';

import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

export default {
  name:'allot-map-dialog',
  props: {
    taskIdList: {
      type: Array,
      default: () => []
    },
    taskConfig: {
      type: Object,
      default: () => ({})
    },
    advancedSearchParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      taskTypesMap: {},
      has_call_center_module: localStorage.getItem('call_center_module') == 1,

      allotMap: null,
      currMarkObj: { // 当前选中的mark 
        index: 0,
        data: {}
      }, 
      mData: [],

      markerMap: {},
      $infoWindow: new AMap.InfoWindow({offset: new AMap.Pixel(0, -28)}),
      planTimeField: {},

      loading: false,
      typesLoading: false,
      visible: false,
      sideOpen: true,
      searchParams: {
        page: 1,
        pageSize: 50
      },
      hasNextPage: true
    }
  },
  computed: {
    selectedData() {
      return this.mData.filter(item => item.selected);
    },
    selectedTaskIds() {
      return this.selectedData.map(item => item.id);
    }
  },
  watch: {
    visible(val) {
      if(val) {
        this.$nextTick(() => {
          this.fetchTaskTypesMap();
          this.initMap();
          this.fetchAllotList();
        });
      }
    }
  },
  methods: {
    /** 打开弹窗（暴露） */
    openDialog() {
      this.visible = true;
    },
    /**  获取工单类型 */
    fetchTaskTypesMap() {
      this.typesLoading = true;
      TaskApi.getTaskTypesMap().then((data) => {
        this.typesLoading = false;
        let isSuccess = data.success
        if (!isSuccess) return
      
        let taskTypes = data?.result || []
        // key : 工单类型id(string) -> value: TaskType
        this.taskTypesMap = taskTypes
          .reduce((acc, currentTaskType) => {
            acc[currentTaskType.templateId] = currentTaskType
            return acc
          }, {})
      }).catch(err => {
        this.typesLoading = false;
        console.error(err)
      })
    },
    /** 批量指派 */
    batchAllotOpen() {
      if(this.selectedData.length < 1) {
        return this.$platform.alert('请选择需要批量指派的工单');
      }

      this.$refs.batchAllotDialog.openDialog(this.taskConfig);
    },
    /** 编辑计划时间的回调 */
    updatePlanTimeBc(newPlanTime) {
      let currIdx = this.currMarkObj.index;
      this.$set(this.currMarkObj.data, 'planTime', newPlanTime);
      this.$set(this.mData[currIdx], 'planTime', newPlanTime);
      this.$nextTick(() => {
        this.openInfoWindow(this.currMarkObj);
      })
      this.$platform.alert('调整计划时间成功');
    },
    /** 获取列表 */
    async fetchAllotList(isLoadmore) {
      this.searchParams.page ++;
      if(!isLoadmore) this.searchParams.page = 1;

      let params = {
        ids: this.taskIdList,
        ...this.searchParams,
        ...this.advancedSearchParams,
        pageSize: 50
      }
      try {
        let res = await TaskApi.getTaskAllotList(params);
        let data = res.result?.content || [];
        if(isLoadmore) {
          this.mData = this.mData.concat(data);
        }else {
          this.mData = data;
        }
        this.hasNextPage = this.searchParams.page < res.result.totalPages;
        this.renderMap();
      } catch (error) {
        console.error(error); 
      }
    },
    /** 加载更多 */
    loadmore() {
      if(this.hasNextPage) {
        this.fetchAllotList(true);
      }
    },
    /** 地图侧栏选择 */
    choose(item, i) {
      this.currMarkObj = {
        data: item,
        index: i
      };
      let taskType = this.taskTypesMap[item.templateId];
      for (const key in taskType.field) {
        if(taskType.field[key].name === 'planTime') {
          this.planTimeField = taskType.field[key];
        }
      }

      this.openInfoWindow(this.markerMap[item.id]);
      this.$set(this.mData[i], 'selected', !this.mData[i].selected);
    },
    /** 根据数据渲染map */
    renderMap(){
      let that = this;
      this.mData.forEach(function (item, index) {
        let marker = that.createMarker(item, index);
        if(marker) that.markerMap[item.id] = marker;
      });

      this.allotMap.setFitView();
    },
    /** 生成地图mark标记点 */
    createMarker(item, index){
      let that = this;
      let adr = item.address;

      if(!adr.longitude || !adr.latitude) return;

      let marker = new AMap.Marker({
        position: [adr.longitude, adr.latitude],
        map: this.allotMap,
        offset: new AMap.Pixel(-12, -16), // 偏移量对应为标记的宽高
        content: `<div id="mapmark${ index }" class="mapmark">${ index + 1 }</div>`,
        extData: {index, data: item}
      });

      marker.on('click', function (e) {
        let marker = e.target;
        let extData = marker.getExtData();

        that.currMarkObj = extData;
        let taskType = that.taskTypesMap[extData.data.templateId];
        for (const key in taskType.field) {
          if(taskType.field[key].name === 'planTime') {
            that.planTimeField = taskType.field[key];
          }
        }
        that.openInfoWindow(marker);
        that.showItem(extData);
      })

      return marker;
    },
    /** 拨打电话 */
    async makePhoneCall(phone) {
      if(!phone) return;
      const params = {
        phone,
        taskType:'task'
      }
      const {code, message} = await TaskApi.dialout(params)
      if (code) {
        this.$platform.alert(message);
      }
    },
    /** 编辑计划时间弹窗 */
    showEditPlantimeModal() {
      this.$refs.planTimeDialog.openDialog();
    },
    /** 信息框事件 */
    infoClick({ target }) {
      const { id } = target;
      if(!id) return;
      let fromId = window.frameElement.getAttribute('id');
      let {index, data} = this.currMarkObj;
      switch(id) {
      case 'customer':
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCustomerView,
          key: data.customerEntity.id,
          params: 'noHistory=1',
          fromId,
        });
        break;
      case 'task':
        openAccurateTab({
          type: PageRoutesTypeEnum.PageTaskView,
          key: data.id,
          titleKey: data.taskNo,
          params: 'noHistory=1',
          fromId,
        });
        break;
      case 'allot':
        openAccurateTab({
          type: PageRoutesTypeEnum.PageTaskView,
          key: data.id,
          titleKey: data.taskNo,
          params: 'noHistory=1&allot=true',
          fromId,
        });
        break;
      case 'phone': // 拨打电话
        this.makePhoneCall(data.linkMan && data.linkMan.phone);
        break;
      case 'editPlanTime': // 修改计划时间
        this.showEditPlantimeModal();
        break
      default:
        break;
      }
    },
    /** map信息框 */
    openInfoWindow(marker) {
      let task = marker.getExtData().data;
      let infoWindow = this.$data.$infoWindow;
      let customerName = (
        task.linkAuth
          ? `<a id="customer" class="open-new-tab" href="javascript:;">${ task.customerEntity.name }</a>`
          : task.customerEntity.name
      )
      let phoneIcon = (
        this.has_call_center_module
          ? '<i id="phone" title="拨打电话" style="width: 14px!important;margin-left: 5px;color: #55b7b4;font-size: 14px;cursor: pointer;" class="iconfont icon-dianhua1"></i>'
          : ''
      )
      let content = (
        `<div class="map-mark-box">
            <div class="map-mark-head">
              <a id="task" class="open-new-tab" href="javascript:;">${ task.taskNo }</a>
                <button id="allot" type="button" class="btn btn-primary">指派</button>
            </div>
            <div class="map-mark-body">
              <h3>${ customerName }</h3>
              <p>联系人：${ task.linkMan && task.linkMan.name }</p>
              <p>电话：${ task.linkMan && task.linkMan.phone }${phoneIcon }</p>
              <p>计划时间：
                <span id="workSidePlantimeText">${ task.planTime }</span>${ 
          !task.isPaused && !task.inApprove ? '<i id="editPlanTime" class="iconfont icon-bianji1" style="width: 14px!important;margin-left: 5px;color: #55b7b4;font-size: 14px;cursor: pointer;"></i>' : '' 
        }</p>
            </div>
        </div>`
      );

      this.allotMap.setZoomAndCenter(12, marker.getPosition());

      infoWindow.setContent(content);
      infoWindow.open(this.allotMap, marker.getPosition());
      marker.setTop(true);
    },
    /** 侧栏需要滚动到指定位置并选择 */
    showItem(item){
      let el = this.$refs[`side_item_${item.index}`];
      this.$refs.sideList.scrollTop = el[0].offsetTop;
      this.$set(this.mData[item.index], 'selected', true);
    },
    /** 初始化map */
    initMap() {
      let center = [116.480983, 40.0958]
      this.allotMap = new AMap.Map(this.$refs.container, {
        resizeEnable: true,
        zoom: 10,
        center,
        animateEnable: false
      });
    }
  },
  components: {
    [PlanTimeDialog.name]: PlanTimeDialog,
    [BatchAllotDialog.name]: BatchAllotDialog
  }
}
</script>

<style lang="scss" scoped>
@import './AllotMapDialog.scss';


/** 弹窗层级问题 */
div[fullscreen]{
  z-index: 888 !important;
}
</style>